<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_Form_Shift_FillRoles extends RedCross_Form
{

    private $_shiftService;
    private $_roles;
    private $_addDefault;
    private $_defaultValues;

    public function __construct($roles, $addDefault = false, $defaultValues = array(), $options = null)
    {
        if (!is_array($roles)) {
        	$roles = array($roles);
        }
        $this->_roles = $roles;
        $this->_addDefault = $addDefault;
        $this->_defaultValues = $defaultValues;
    	return parent::__construct($options);
    }

	public function init()
	{
        $this->_shiftService = RedCross_Factory::getService('Core_Service_Shift');

        $this->fillForm();

        $this->addElement('submit', 'submit', array(
            'required' => true,
            'ignore'   => true,
            'label'    => 'Endre',
        ));
 	}

 	protected function fillForm()
 	{
        $this->createFormElements($this->_roles);

        $this->setElementDecorators($this->_elementDecorators);
 	}

 	protected function createFormElements($roles)
 	{
        foreach ($roles as $role) {
            $name = strtolower('role' . $role['id']);
            $temp = $this->createElement('select', $name);

            // Add default value
            if ($this->_addDefault) {
            	$temp->addMultiOption(null, '-- Velg person --');
            }

            // Add all other values
            $temp->addMultiOptions($this->createArrayWithMemberFittingRole((int) $role['Role']['id']));

            // Set default value
            if (array_key_exists((int)$role['id'], $this->_defaultValues)) {
                $temp->setValue($this->_defaultValues[$role['id']]);
            }

            $temp->setLabel($role['Role']['name'])->setRequired(true);
            $this->addElement($temp);
        }
 	}

	protected function createArrayWithMemberFittingRole($roleId) {
		$members = $this->_shiftService->fetchMembersWithCourses($roleId);

	    $array = array();
		foreach ($members as $member) {
			$array[$member['id']] = $member['last_name'] . ', ' . $member['first_name'];
		}
		return $array;
	}

 }